package com.zhima.util;

/**
 * @author : 芝麻
 * @date : 2023-08-06 16:24
 **/
public class StrUtil {

    public static final char UNDER_LINE = '_';

    public static String removeRedundantUnderline(String input) {
        StringBuilder ans = new StringBuilder();
        for (char i : input.toCharArray()) {
            if (i != UNDER_LINE) {
                ans.append(i);
            }
        }
        return ans.toString();
    }

    public static String addUnderLine(String numberString) {
        StringBuilder ans = new StringBuilder();
        int length = numberString.length();
        int index = length - 1;
        while (index >= 2) {
            for (int i = index; i >= index - 2; i--) {
                ans.append(numberString.charAt(i));
            }
            index -= 3;
            if (index >= 0) {
                ans.append(UNDER_LINE);
            }
        }
        for (int i = index; i >= 0; i--) {
            ans.append(numberString.charAt(i));
        }
        return ans.reverse().toString();
    }

    private static final String HTML_HEAD = "<html>";
    private static final String HTML_TAIL = "</html>";
    private static final String NEW_LINE = "<br/>";
    private static final String CENTER_HEAD = "<center>";
    private static final String CENTER_TAIL = "</center>";
    private static final int CHAR_NUMBER_PER_LINE = 32;

    public static String addNewLineIfToLong(String str) {
        if (str == null) {
            return "";
        }
        int strLen = str.length();
        char[] sArray = str.toCharArray();
        if (str.isBlank() || strLen < 50) {
            return str;
        }
        StringBuilder ans = new StringBuilder(HTML_HEAD);
        // 每行放CHAR_NUMBER_PER_LINE个字符
        int index = 0;
        while (index < strLen) {
            ans.append(CENTER_HEAD);
            for (int i = 0; i < CHAR_NUMBER_PER_LINE && index < strLen; i++) {
                ans.append(sArray[index++]);
            }
            ans.append(CENTER_TAIL);
            ans.append(NEW_LINE);
        }
        ans.append(HTML_TAIL);
        return ans.toString();
    }

    public static String removeNewLine(String str) {
        return str.replaceAll(String.format("(%s|%s|%s|%s|%s)", HTML_HEAD, HTML_TAIL, NEW_LINE, CENTER_HEAD, CENTER_TAIL), "");
    }
}
